<template>
  <dv-border-box-1 style="height:100%">
    <el-card class="box-card" shadow="hover">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="文章属性" name="1">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form
                :model="pojo"
                ref="pojoForm"
                :rules="rulesDialog"
                label-position="right"
                label-width="99px"
                size="mini"
              >
                <el-form-item label="标题" prop="article.title">
                  <el-input style="width:50%" v-model="pojo.article.title" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="是否公开" prop="ispublic">
                  <el-tooltip :content="pojo.article.ispublic === '1' ? '公开' : '不公开'" placement="top">
                    <el-switch
                      v-model="pojo.article.ispublic"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      active-value="1"
                      inactive-value="0"
                      @change="handleisPublicChange"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>

                <el-form-item label="是否置顶" prop="istop">
                  <el-tooltip :content="pojo.article.istop === '1' ? '置顶' : '不置顶'" placement="top">
                    <el-switch
                      v-model="pojo.article.istop"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      active-value="1"
                      inactive-value="0"
                      @change="handleisTopChange"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="是否开启评论" prop="iscomment">
                  <el-tooltip :content="pojo.article.iscomment === '1' ? '开启' : '关闭'" placement="top">
                    <el-switch
                      v-model="pojo.article.iscomment"
                      active-color="#13ce66"
                      inactive-color="#ff4949"
                      active-value="1"
                      inactive-value="0"
                      @change="handleisCommentChange"
                    ></el-switch>
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="分类" prop="categoryInfo.categoryName">
                  <el-cascader
                    filterable
                    placeholder="点击这里选择分类信息"
                    size="medium"
                    :options="options"
                    v-model="pojo.categoryInfo.categoryName"
                    :props="{ checkStrictly: true }"
                    clearable
                  ></el-cascader>
                </el-form-item>
                <!-- 文章所属标签管理 -->
                <el-form-item label="标签" prop="tags">
                  <el-tag
                    :key="index"
                    v-for="(tag, index) in pojo.article.tags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >{{ tag.tagname }}</el-tag>

                  <el-button class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12">
              <div style="overflow:auto;">
                <!-- <el-calendar  v-model="date"></el-calendar> -->
              </div>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
    </el-card>

    <!-- 选择分类对话框 -->
    <el-dialog title="选择分类" :visible.sync="dialogCategoryVisible" width="500px">
      <category @option-category="optionCategory" :isDialog="true"></category>
    </el-dialog>
    <!-- 选择标签对话框 -->
    <el-dialog title="选择标签" :visible.sync="dialogTagVisible" width="500px">
      <tag @option-tag="optionTag" :isTagDialog="true"></tag>
    </el-dialog>
    <span style="color:red">发布前切记先ctrl+s预保存文章！！</span>
    <mavon-editor
      v-model="pojo.article.contentMd"
      fontSize="16px"
      @imgAdd="handleImgAdd"
      @save="handleSave"
    />
    <div style="float:right;margin-top:10px">
      <el-button type="primary" @click="handlepublishArticle">发布</el-button>
      <el-button style="margin:0px 15px 0 10px" @click="resetForm('pojoForm')">重置</el-button>
    </div>
  </dv-border-box-1>
</template>

<script>
import marked from "marked";
import hljs from "highlight.js";
import { publishArticle } from "@/api/article";
import Category from "@/views/article/category.vue";
import Tag from "@/views/article/tag.vue";
import tagApi from "@/api/tag";
import categoryApi from "@/api/category";

export default {
  components: {
    Category,
    Tag
  },
  data() {
    return {
      options: [], //分类选择列表
      date: new Date(),
      activeName: "",
      value: "",
      pojo: {
        article: {
          aid: null,
          title: "",
          contentMd: "",
          contentHtml: "",
          ispublic: "",
          istop: "",
          iscomment: "",
          tags: [] //标签总列表
        },
        categoryInfo:{
          aid:null,
          categoryName: "",

        }
      },
      rulesDialog: {
        "article.title": [
          { required: true, message: "文章标题不能为空", trigger: "blur" },
          { min: 5, max: 30, message: "长度在 5 到 30 个字符", trigger: "blur" }
        ],
        "categoryInfo.categoryName": [
          { required: true, message: "文章分类不能为空", trigger: "blur" }
        ]
      },
      dialogTagVisible: false, //选择标签对话框
      dialogCategoryVisible: false, //选择分类对话框
      outerVisible: false, //外层dialog
      innerVisible: false //内层dialog
    };
  },
  /*computed: {
    compileMarkdown: function() {
      if (this.pojo.content_md !== null) {
        return marked(this.pojo.content_md, {
          highlight: function(code) {
            //新加的，用来配置语法高亮
            return hljs.highlightAuto(code).value;
          }
        });
      }
    }
  },*/
  created() {
    this.fetchTagData();
    this.fetchCategoryTree();
  },

  methods: {
    fetchCategoryTree() {
      categoryApi.fetchCategoryTree().then(resp => {
        if (resp.data.flag) {
          //正则替换key的名
          this.options = JSON.parse(
            JSON.stringify(resp.data.data)
              .replace(/id/g, "value")
              .replace(/cname/g, "label")
          );
        }
      });
    },
    /**
     * 是否公开变化
     */
    handleisPublicChange(val) {
      this.pojo.article.ispublic = val;
     // console.log(this.pojo.article.ispublic)
    },
    /**
     * 是否置顶
     */
    handleisTopChange(val) {
      this.pojo.article.istop = val;
    },
    /**
     * 是否开启评论
     */
    handleisCommentChange(val) {
      this.pojo.article.iscomment = val;
    },
    /**
     * 表单审核状态改变，dialog中的
     */
    handleStateChangeDialog(val) {
      this.pojo.article.state = val;
    },
    /**
     * 展示添加标签输入框
     */
    showInput() {
      this.dialogTagVisible = true; //打开标签管理组件
    },
    /**
     * 选择标签后数据回显
     */
    optionTag(currentRow) {
      if (currentRow.state === "0") {
        this.$message({
          type: "warning",
          message: "该标签已弃用,不可使用！"
        });
        return false;
      }
      let inputValue = currentRow;

      if (inputValue) {
        // console.log(inputValue)
        for (let tag of this.pojo.article.tags) {
          if (tag.tagname === inputValue.tagname) {
            this.$message({
              type: "warning",
              message: "您已添加了该标签哦"
            });
            return;
          }
        }
        this.pojo.article.tags.push(inputValue);
      }
      this.dialogTagVisible = false; // 标签组件关闭
    },
    /**
     * 获取前三条tag记录
     */
    fetchTagData() {
      tagApi.findTop3Data(1, 3).then(resp => {
        if (resp.data.flag) {
          this.pojo.article.tags = resp.data.data.rows;
        }
      });
    },
    /**
     * 选择分类并回显
     */
    optionCategory(currentRow) {
      if (currentRow.state === "0") {
        this.$message({
          type: "warning",
          message: "该分类已弃用不可使用！"
        });
        return false;
      }
      if (this.isSearch) {
        this.searchMap.categoryName = currentRow.cname;
        this.isSearch = false;
      } else {
        this.pojo.categoryInfo.categoryName = currentRow.cname; //分类id
      }
      this.dialogCategoryVisible = false;
    },
    /**
     * 编辑区发生变化的回调事件(render: value 经过markdown解析后的结果)
     */
    handleChange(markdorn, html) {
      // console.log("value:",markdorn)
      // console.log(html)
    },
    handleImgAdd(filename, imgfile) {
      // console.log(filename)
      //console.log(imgfile)
    },
    /**
     * ctrl+s保存的回调
     */
    handleSave(markdown, html) {
      this.pojo.article.contentMd = markdown;
      this.pojo.article.contentHtml = html;
      //console.log(this.pojo.content_md);
    },
    /**
     *移除标签触发
     */
    handleClose(tag) {
      this.pojo.article.tags.splice(this.pojo.article.tags.indexOf(tag), 1);
    },
    handlepublishArticle() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          if (this.pojo.article.contentMd !== null && this.pojo.article.contentMd !== "") {
            if (
              this.pojo.categoryInfo.categoryName === null &&
              this.pojo.categoryInfo.categoryName === ""
            ) {
              this.$message({
                message: "请为您的文章添加分类",
                type: "warning"
              });
            } else if (this.pojo.article.tags != null && this.pojo.article.tags.length !== 0) {
              this.pojo.categoryInfo.categoryName = this.pojo.categoryInfo.categoryName.join("/");
              publishArticle(this.pojo).then(resp => {
                const respData = resp.data;
                if (respData.flag) {
                  this.$message({
                    message: respData.message,
                    type: "success"
                  });
                  this.resetForm("pojoForm");
                  this.pojo.article.contentHtml = "";
                  this.pojo.article.contentMd = "";
                } else {
                  this.$message({
                    message: respData.message,
                    type: "warning"
                  });
                }
              });
            } else {
              this.$confirm(
                "您还没有为您的文章添加合适的标签，是否添加",
                "提示",
                {
                  confirmButtonText: "添加",
                  cancelButtonText: "暂不添加",
                  type: "warning"
                }
              )
                .then(() => {
                  this.showInput();
                })
                .catch(() => {
                  this.pojo.categoryInfo.categoryName = this.pojo.categoryInfo.categoryName.join("/");
                  publishArticle(this.pojo).then(resp => {
                    const respData = resp.data;
                    if (respData.flag) {
                      this.$message({
                        message: respData.message,
                        type: "success"
                      });
                      this.resetForm("pojoForm");
                      this.pojo.article.contentHtml = "";
                    } else {
                      this.$message({
                        message: respData.message,
                        type: "warning"
                      });
                    }
                  });
                });
            }
          } else {
            this.$message({
              message: "您好像还没有编写文章内容哦",
              type: "warning"
            });
          }
        } else {
          this.$message({
            message: "请检查文章属性格式",
            type: "warning"
          });
        }
      });
    },
    /**
     * form重置
     */
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
